package com.tencent.qf.common.gateway.mks;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.base.Strings;
import com.tencent.qf.common.exception.ServiceException;
import com.tencent.qf.common.gateway.mks.dto.MksCouponStatusCountBatchReq;
import com.tencent.qf.common.gateway.mks.dto.MksCouponStatusCountDTO;
import com.tencent.qf.common.gateway.mks.dto.MksCouponStatusCountReq;
import com.tencent.qf.common.gateway.mks.dto.MksJdCouponStatusCountBatchReq;
import com.tencent.qf.common.gateway.mks.dto.MksJdCouponStatusCountDTO;
import com.tencent.qf.common.pojo.HttpResult;
import com.tencent.qf.common.util.RateLimiterUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import static com.tencent.qf.common.exception.ErrorCode.INTERNAL_SERVER_ERROR;

@Slf4j
@Service
public class MKSGatewayService {

    @Autowired
    private MKSClient mksClient;


    @Resource()
    private RateLimiterUtil rateLimiterUtil;

    /**
     * 营销用户代金券计数接口
     * @param request
     * @return
     */
    public List<MksCouponStatusCountDTO> mksCouponStatusCount(MksCouponStatusCountReq request){
        String result = mksClient.post(request, MKSApiPath.mksCouponStatusCount);
        if(!StringUtils.hasText(result)){
            log.error("营销用户代金券计数接口失败");
            throw new ServiceException(INTERNAL_SERVER_ERROR.getCode(), "营销用户代金券计数接口失败");
        }
        HttpResult<List<MksCouponStatusCountDTO>> httpResult = JSON.parseObject(result, new TypeReference<HttpResult<List<MksCouponStatusCountDTO>>>() {});
        if(2000103 == httpResult.getCode()){
            // unionId不存在
            List<MksCouponStatusCountDTO> rs = new ArrayList<>();
            for(String status : request.getStatus()){
                rs.add(new MksCouponStatusCountDTO(status, 0));
            }
            return rs;
        }
        if(!httpResult.isSuccess()){
            log.error("营销用户代金券计数接口失败");
            throw new ServiceException(INTERNAL_SERVER_ERROR.getCode(), "营销用户代金券计数接口失败");
        }
        return httpResult.getData();
    }

    /**
     * 营销用户代金券计数批量接口
     * @param request
     * @return
     */
    public Map<String, List<MksCouponStatusCountDTO>> mksCouponStatusCountBatch(MksCouponStatusCountBatchReq request){
        String result = mksClient.post(request, MKSApiPath.mksCouponStatusCountBatch);
        if(!StringUtils.hasText(result)){
            log.error("营销用户代金券计数批量接口失败");
            throw new ServiceException(INTERNAL_SERVER_ERROR.getCode(), "营销用户代金券计数批量接口失败");
        }
        HttpResult<Map<String, List<MksCouponStatusCountDTO>>> httpResult = JSON.parseObject(result, new TypeReference<HttpResult<Map<String, List<MksCouponStatusCountDTO>>>>() {});
        if(!httpResult.isSuccess()){
            log.error("营销用户代金券计数批量接口失败");
            throw new ServiceException(INTERNAL_SERVER_ERROR.getCode(), "营销用户代金券计数批量接口失败");
        }
        return httpResult.getData();
    }

    /**
     * 营销用户代金券计数批量接口
     * @param request
     * @return
     */
    public Map<String, List<MksJdCouponStatusCountDTO>> mksJdCouponStatusCountBatch(MksJdCouponStatusCountBatchReq request){
        String result = mksClient.post(request, MKSApiPath.mksJdCouponStatusCountBatch);
        if(!StringUtils.hasText(result)){
            log.error("营销用户京享礼金券计数批量接口失败");
            throw new ServiceException(INTERNAL_SERVER_ERROR.getCode(), "营销用户京享礼金券计数批量接口失败");
        }
        HttpResult<Map<String, List<MksJdCouponStatusCountDTO>>> httpResult = JSON.parseObject(result, new TypeReference<HttpResult<Map<String, List<MksJdCouponStatusCountDTO>>>>() {});
        if(!httpResult.isSuccess()){
            log.error("营销用户京享礼金券计数批量接口失败");
            throw new ServiceException(INTERNAL_SERVER_ERROR.getCode(), "营销用户京享礼金券计数批量接口失败");
        }
        return httpResult.getData();
    }

    @Async("asyncMarketServiceExecutor")
    public CompletableFuture<HashMap<String, List<MksCouponStatusCountDTO>>> getCouponCountBatch(List<String> unionIds) {
        HashMap<String, List<MksCouponStatusCountDTO>> couponsCount = new HashMap<>();
        MksCouponStatusCountReq req = new MksCouponStatusCountReq();
        req.setStatus(new String[]{"USED"});
//        req.setCreate_time_end(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        for (String unionId : unionIds) {
            if(!Strings.isNullOrEmpty(unionId)) {
                req.setWechat_user_union_id(unionId);
                rateLimiterUtil.acquire(1);
                List<MksCouponStatusCountDTO> dtos = mksCouponStatusCount(req);
                couponsCount.put(unionId, dtos);
            }
        }
        return CompletableFuture.completedFuture(couponsCount);
    }
}
